<template>
  <div class="ewe-weaning-view">
    <!-- 顶部操作栏 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button type="primary" @click="handleAddNew" :icon="Plus">
          + 新增
        </el-button>
        <el-button type="success" @click="handleSave" :icon="Document">
          保存
        </el-button>
        <el-button @click="handleUndo" :icon="RefreshLeft">
          撤销
        </el-button>
        <el-button type="danger" @click="handleDelete" :icon="Delete">
          删除
        </el-button>
      </div>
      <div class="action-right">
        <el-icon class="action-icon">
          <Setting />
        </el-icon>
        <el-icon class="action-icon">
          <Printer />
        </el-icon>
      </div>
    </div>

    <!-- 头部表单区域 -->
    <div class="form-section">
      <div class="form-row">
        <div class="form-item">
          <label class="required">负责人</label>
          <el-select v-model="formData.responsibleFor" placeholder="请选择负责人" clearable>
            <el-option label="海绵宝宝" value="海绵宝宝" />
            <el-option label="派大星" value="派大星" />
            <el-option label="蟹老板" value="蟹老板" />
          </el-select>
        </div>
        <div class="form-item">
          <label class="required">断奶日期</label>
          <el-date-picker v-model="formData.mainWeaningTime" type="date" placeholder="选择日期" format="YYYY/MM/DD"
            value-format="YYYY/MM/DD" />
        </div>
        <div class="form-item">
          <label>单据号</label>
          <el-input v-model="formData.documentNumber" readonly />
        </div>
        <div class="form-item">
          <label>流水号</label>
          <el-input v-model="formData.serialNumber" readonly />
        </div>
      </div>
    </div>

    <!-- 主数据表格区域 -->
    <div class="table-section">
      <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="*耳号" width="120">
          <template #default="{ row, $index }">
            <el-input v-model="row.weaningSnowId" placeholder="请输入耳号"
              @blur="validateRequiredField(row, 'weaningSnowId', $index)" />
          </template>
        </el-table-column>
        <el-table-column label="哺乳天数" width="100">
          <template #default="{ row }">
            <el-input-number v-model="row.weaningDayNum" :min="0" :max="365" controls-position="right" />
          </template>
        </el-table-column>
        <el-table-column label="当前栋舍" width="120">
          <template #default="{ row }">
            <el-input v-model="row.weaningPoultryhome" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="当前栏位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.weaningField" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="转入栋舍" width="120">
          <template #default="{ row }">
            <el-input v-model="row.weaningTransferHouse" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="转入栏位" width="120">
          <template #default="{ row }">
            <el-input v-model="row.weaningTransfer" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="*断奶只数(只)" width="140">
          <template #default="{ row, $index }">
            <el-input-number v-model="row.weaningQuantity" :min="0" :max="100" controls-position="right"
              @change="updateTotals" @blur="validateRequiredField(row, 'weaningQuantity', $index)" />
          </template>
        </el-table-column>
        <el-table-column label="*断奶总窝重(公斤)" width="160">
          <template #default="{ row, $index }">
            <el-input-number v-model="row.weaningWeight" :min="0" :precision="2" controls-position="right"
              @change="updateTotals" @blur="validateRequiredField(row, 'weaningWeight', $index)" />
          </template>
        </el-table-column>
        <el-table-column label="种母重量(公斤)" width="140">
          <template #default="{ row }">
            <el-input-number v-model="row.weaningMomWeight" :min="0" :precision="2" controls-position="right"
              @change="updateTotals" />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部操作和统计区域 -->
    <div class="footer-section">
      <div class="summary-section">
        <div class="summary-label">合计</div>
        <div class="row-actions">
          <el-button type="primary" @click="handleAddRow" :icon="Plus">
            + 增行
          </el-button>
          <el-button type="danger" @click="handleDeleteRows" :icon="Delete">
            - 删行
          </el-button>
        </div>
      </div>

      <div class="totals-section">
        <div class="total-item">
          <span class="total-label">断奶只数(只):</span>
          <span class="total-value">{{ totals.weaningCount.toFixed(2) }}</span>
        </div>
        <div class="total-item">
          <span class="total-label">断奶总窝重(公斤):</span>
          <span class="total-value">{{ totals.totalWeaningWeight.toFixed(2) }}</span>
        </div>
        <div class="total-item">
          <span class="total-label">种母重量(公斤):</span>
          <span class="total-value">{{ totals.motherWeight.toFixed(2) }}</span>
        </div>
      </div>

      <div class="remarks-section">
        <label>备注</label>
        <el-input v-model="formData.remarks" type="textarea" :rows="3" placeholder="请输入备注信息" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Document,
  RefreshLeft,
  Delete,
  Setting,
  Printer
} from '@element-plus/icons-vue'
import { Writes } from '@/Utils/axiosHelper';
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
// 接口类型定义
// 单个断奶记录（对应 API 中 weaningsList 的元素）
interface WeaningRecord {
  weaningSnowId: string          // 耳号
  weaningDayNum: number          // 哺乳天数
  weaningPoultryhome: string     // 当前栋舍
  weaningField: string          // 当前栏位
  weaningTransferHouse: string  // 转入栋舍
  weaningTransfer: string       // 转入栏位
  weaningQuantity: number       // 断奶只数
  weaningWeight: number         // 断奶总窝重
  weaningMomWeight: number      // 种母重量
  remarks: string               // 备注
}

// 批量断奶请求体（对应 API 请求格式）
interface BatchWeaningRequest {
  weaningsList: WeaningRecord[]
  responsibleFor: string        // 负责人
  mainWeaningTime: string       // 断奶日期
  documentNumber: string        // 单据号
  serialNumber: string          // 流水号
}

interface Totals {
  weaningCount: number
  totalWeaningWeight: number
  motherWeight: number
}

// 响应式数据
const formData = reactive({
  "responsibleFor": "",
  "mainWeaningTime": "",
  "documentNumber": "",
  "serialNumber": "",
  remarks: ''
})

const tableData = ref<WeaningRecord[]>([])
const selectedRows = ref<WeaningRecord[]>([])
const isEditMode = ref(false)
const originalData = ref<any>(null)


// 计算合计
const totals = computed<Totals>(() => {
  return tableData.value.reduce((acc, row) => {
    acc.weaningCount += row.weaningQuantity || 0
    acc.totalWeaningWeight += row.weaningWeight || 0
    acc.motherWeight += row.weaningMomWeight || 0
    return acc
  }, {
    weaningCount: 0,
    totalWeaningWeight: 0,
    motherWeight: 0
  })
})
// 添加新行
const addNewRow = () => {
  const newRow: WeaningRecord = {
    weaningSnowId: '',          // 耳号
    weaningDayNum: 0,           // 哺乳天数
    weaningPoultryhome: '',     // 当前栋舍
    weaningField: '',          // 当前栏位
    weaningTransferHouse: '',  // 转入栋舍
    weaningTransfer: '',       // 转入栏位
    weaningQuantity: 0,        // 断奶只数
    weaningWeight: 0,          // 断奶总窝重
    weaningMomWeight: 0,       // 种母重量
    remarks: ''                // 备注
  }
  tableData.value.push(newRow)
}

// 更新合计
const updateTotals = () => {
  // 合计会自动通过 computed 更新
}

// 顶部操作栏方法
const handleAddNew = () => {
  ElMessageBox.confirm('确定要新增记录吗？当前未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    resetForm()
    ElMessage.success('已重置表单')
  }).catch(() => {
    // 用户取消
  })
}

const handleSave = async () => {
  // 表单验证
  if (!validateForm()) {
    return
  }

  try {
    // 准备提交数据
    const submitData: BatchWeaningRequest = {
      weaningsList: tableData.value.map((row, index) => ({
        weaningSnowId: row.weaningSnowId,
        weaningDayNum: row.weaningDayNum,
        weaningPoultryhome: row.weaningPoultryhome,
        weaningField: row.weaningField,
        weaningTransferHouse: row.weaningTransferHouse,
        weaningTransfer: row.weaningTransfer,
        weaningQuantity: row.weaningQuantity,
        weaningWeight: row.weaningWeight,
        weaningMomWeight: row.weaningMomWeight,
        remarks: row.remarks
      })),
      responsibleFor: formData.responsibleFor,
      mainWeaningTime: formatDateForAPI(formData.mainWeaningTime),
      documentNumber: formData.documentNumber,
      serialNumber: formData.serialNumber
    }

    console.log('提交数据:', submitData)

    // 调用批量添加 API
    const response = await Writes.post("Management/AddBatchWeanings", submitData)

    if (response.data.code == 100) {
      ElMessage.success(response.data.msg || '保存成功')
      isEditMode.value = true
      saveOriginalData()
      router.push('/EweWeaningList')
    } else {
      ElMessage.error(response.data.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请检查网络连接或联系管理员')
  }
}

const handleUndo = () => {
  if (originalData.value) {
    Object.assign(formData, originalData.value.formData)
    tableData.value = [...(originalData.value.tableData || [])]
    ElMessage.success('已撤销更改')
  } else {
    ElMessage.warning('没有可撤销的更改')
  }
}

const handleDelete = () => {
  if (!isEditMode.value) {
    ElMessage.warning('请先保存记录')
    return
  }

  ElMessageBox.confirm('确定要删除当前记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteWeaningRecord()
      resetForm()
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('Delete error:', error)
    }
  }).catch(() => {
    // 用户取消
  })
}

// 表格操作方法
const handleAddRow = () => {
  addNewRow()
}

const handleDeleteRows = () => {
  if (tableData.value.length > 0) {
    tableData.value.pop();
  }
}

const handleSelectionChange = (selection: WeaningRecord[]) => {
  selectedRows.value = selection || []
}

// 表单验证
const validateForm = (): boolean => {
  // 验证基本信息
  if (!formData.responsibleFor) {
    ElMessage.warning('请选择负责人')
    return false
  }

  if (!formData.mainWeaningTime) {
    ElMessage.warning('请选择断奶日期')
    return false
  }

  // 验证表格数据
  if (tableData.value.length === 0) {
    ElMessage.warning('请至少添加一条断奶记录')
    return false
  }

  // 验证每行数据
  for (let i = 0; i < tableData.value.length; i++) {
    const row = tableData.value[i]

    if (!row) continue

    if (!row.weaningSnowId) {
      ElMessage.warning(`第 ${i + 1} 行：耳号不能为空`)
      return false
    }

    if (!row.weaningQuantity || row.weaningQuantity <= 0) {
      ElMessage.warning(`第 ${i + 1} 行：断奶只数不能为空或小于等于0`)
      return false
    }

    if (!row.weaningWeight || row.weaningWeight <= 0) {
      ElMessage.warning(`第 ${i + 1} 行：断奶总窝重不能为空或小于等于0`)
      return false
    }
  }

  return true
}

// 日期格式化：将 YYYY/MM/DD 格式转换为 API 需要的 ISO 格式
const formatDateForAPI = (dateStr: string | undefined): string => {
  if (!dateStr) return ''

  try {
    // 如果已经是 ISO 格式，直接返回
    if (dateStr.includes('T')) return dateStr

    // 将 YYYY/MM/DD 转换为 ISO 格式
    const dateParts = dateStr.split('/')
    if (dateParts.length !== 3) {
      console.error('无效的日期格式:', dateStr)
      return dateStr
    }

    const [year, month, day] = dateParts
    const date = new Date(parseInt(year || '0'), parseInt(month || '1') - 1, parseInt(day || '1'))

    if (isNaN(date.getTime())) {
      console.error('无效的日期格式:', dateStr)
      return dateStr
    }

    // 格式化为 ISO 字符串，但只保留日期部分
    return date.toISOString().split('T')[0] + 'T00:00:00.000Z'
  } catch (error) {
    console.error('日期格式化失败:', error)
    return dateStr
  }
}

const validateRequiredField = (row: WeaningRecord | undefined, field: string, index: number) => {
  if (!row) return

  if (field === 'weaningQuantity' && (!row.weaningQuantity || row.weaningQuantity <= 0)) {
    ElMessage.warning(`第 ${index + 1} 行断奶只数不能为空或小于等于0`)
  } else if (field === 'weaningWeight' && (!row.weaningWeight || row.weaningWeight <= 0)) {
    ElMessage.warning(`第 ${index + 1} 行断奶总窝重不能为空或小于等于0`)
  } else if (field === 'weaningShowId' && !row.weaningSnowId) {
    ElMessage.warning(`第 ${index + 1} 行耳号不能为空`)
  }
}

const getFieldLabel = (field: string): string => {
  const labels: { [key: string]: string } = {
    weaningShowId: '耳号',
    weaningQuantity: '断奶只数',
    weaningWeight: '断奶总窝重'
  }
  return labels[field] || field
}
// 生成单据号和流水号
const generateDocumentNumbers = () => {
  const timestamp = Date.now()
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')

  // 单据号格式：PC + 年月日 + 时间戳后6位
  formData.documentNumber = `PC${year}${month}${day}${String(timestamp).slice(-6)}`

  // 流水号格式：SN + 时间戳
  formData.serialNumber = `SN${timestamp}`
}
// 重置表单
const resetForm = () => {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  Object.assign(formData, {
    responsibleFor: '',
    mainWeaningTime: `${year}/${month}/${day}`,
    documentNumber: '---',
    serialNumber: '---',
    remarks: ''
  })
  generateDocumentNumbers()
  tableData.value = []
  addNewRow()
  isEditMode.value = false
  originalData.value = null
}
onMounted(() => {
  generateDocumentNumbers()
})
// 保存原始数据（用于撤销功能）
const saveOriginalData = () => {
  originalData.value = {
    formData: { ...formData },
    tableData: JSON.parse(JSON.stringify(tableData.value || []))
  }
}

// ========== 后端接口方法 ==========

// 创建断奶记录
const createWeaningRecord = async () => {
  const payload: BatchWeaningRequest = {
    weaningsList: tableData.value.map((row, index) => ({
      ...row,
      // 这里可以添加额外的处理逻辑，比如设置序号等
    })),
    responsibleFor: formData.responsibleFor,
    mainWeaningTime: formData.mainWeaningTime,
    documentNumber: formData.documentNumber,
    serialNumber: formData.serialNumber
  }

  // TODO: 调用后端创建接口
  // const response = await api.post('/api/weaning-records', payload)
  console.log('创建断奶记录:', payload)

  // 模拟接口调用
  return new Promise((resolve) => {
    setTimeout(() => {
      formData.documentNumber = `WR${Date.now()}`
      formData.serialNumber = `SN${Date.now()}`
      resolve(true)
    }, 1000)
  })
}

// 更新断奶记录
const updateWeaningRecord = async () => {
  const payload: BatchWeaningRequest = {
    weaningsList: tableData.value.map((row, index) => ({
      ...row,
      // 这里可以添加额外的处理逻辑，比如设置序号等
    })),
    responsibleFor: formData.responsibleFor,
    mainWeaningTime: formData.mainWeaningTime,
    documentNumber: formData.documentNumber,
    serialNumber: formData.serialNumber
  }

  // TODO: 调用后端更新接口
  // const response = await api.put(`/api/weaning-records/${payload.id}`, payload)
  console.log('更新断奶记录:', payload)

  // 模拟接口调用
  return new Promise((resolve) => {
    setTimeout(() => resolve(true), 1000)
  })
}

// 删除断奶记录
const deleteWeaningRecord = async () => {
  const id = formData.documentNumber

  // TODO: 调用后端删除接口
  // const response = await api.delete(`/api/weaning-records/${id}`)
  console.log('删除断奶记录:', id)

  // 模拟接口调用
  return new Promise((resolve) => {
    setTimeout(() => resolve(true), 1000)
  })
}

// 获取断奶记录详情（用于编辑模式）
const getWeaningRecordDetail = async (id: string) => {
  // TODO: 调用后端获取详情接口
  // const response = await api.get(`/api/weaning-records/${id}`)
  console.log('获取断奶记录详情:', id)

  // 模拟接口调用
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        formData: {
          responsibleFor: 'zhangsan',
          mainWeaningTime: '2023/03/31',
          documentNumber: 'WR20230331001',
          serialNumber: 'SN20230331001',
          remarks: '测试备注'
        },
        records: [
          {
            weaningShowId: 'E001',
            weaningDayNum: 60,
            weaningPoultryhome: 'A栋',
            weaningField: 'A01',
            weaningTransferHouse: 'B栋',
            weaningTransfer: 'B01',
            weaningQuantity: 3,
            weaningWeight: 15.5,
            weaningMomWeight: 45.2,
            remarks: '测试备注'
          }
        ]
      })
    }, 1000)
  })
}
</script>

<style scoped>
.ewe-weaning-view {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 顶部操作栏 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.action-left {
  display: flex;
  gap: 10px;
}

.action-right {
  display: flex;
  gap: 15px;
}

.action-icon {
  font-size: 18px;
  color: #666;
  cursor: pointer;
  transition: color 0.3s;
}

.action-icon:hover {
  color: #409eff;
}

/* 表单区域 */
.form-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.form-item label.required::after {
  content: ' *';
  color: #f56c6c;
}

/* 表格区域 */
.table-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 底部区域 */
.footer-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.summary-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.summary-label {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.row-actions {
  display: flex;
  gap: 10px;
}

.totals-section {
  display: flex;
  gap: 30px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.total-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.total-label {
  font-weight: 500;
  color: #666;
  font-size: 14px;
}

.total-value {
  font-weight: 600;
  color: #333;
  font-size: 16px;
  min-width: 80px;
  text-align: right;
}

.remarks-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.remarks-section label {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .totals-section {
    flex-wrap: wrap;
    gap: 20px;
  }
}

@media (max-width: 1200px) {
  .form-row {
    grid-template-columns: repeat(2, 1fr);
  }

  .totals-section {
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }

  .action-left {
    flex-wrap: wrap;
  }

  .ewe-weaning-view {
    padding: 10px;
  }

  .totals-section {
    flex-direction: column;
    gap: 10px;
  }

  .summary-section {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}
</style>